﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.Utils;
using Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.ViewModel;
using Newtonsoft.Json;
using NLog;

namespace Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.Visiters
{
    /// <summary>
    /// 电信NB平台的API接口基本访问管理类型
    /// 用于获取Token，及基本访问属性获取
    /// </summary>
    public class CT_NBIoT_BaseVister
    {
        protected  HttpsUtil _HttpsUtil;
        protected  Logger _logger = LogManager.GetCurrentClassLogger();

        protected  string _MAppid;
        protected  string _MAppsecret;

        public CT_NBIoT_BaseVister(string appId, string appSecret, string platformIp, int port)
        {
            _MAppid = appId;
            _MAppsecret = appSecret;
            _HttpsUtil = new HttpsUtil(platformIp, port);
        }
        /// <summary>
        ///     获取Token
        /// </summary>
        /// <returns></returns>
        public TokenResult GetToken()
        {
            TokenResult result;
            var apiPath = "/iocm/app/sec/v1.1.0/login";
            var body = $"appId={_MAppid}&secret={_MAppsecret}";
            var method = "POST";
            var contenttype = "application/x-www-form-urlencoded";
            var headers = new WebHeaderCollection();
            try
            {
                var apiresult = _HttpsUtil.PostUrl(apiPath, body, headers, method, contenttype);
                var tr = JsonConvert.DeserializeObject<TokenResult>(apiresult.Result);
                result = tr;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                result = null;
            }

            return result;
        }
    }
}
